#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <sys/ioctl.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <fcntl.h>
#include <errno.h>

#define GMEM_MAGIC 'G'
#define GMEM_SET_SIZE _IOW(GMEM_MAGIC, 0, int32_t)
#define GMEM_GET_SIZE _IOR(GMEM_MAGIC, 1, int32_t)
#define GMEM_CLEAN _IO(GMEM_MAGIC, 2)

static char rbuf[100];
static char wbuf[100] = "1234567890abcdefghijklmnopqrstuvwxy";
int main(void)
{
	int fd;
	int err = 0;
	int32_t gmem_size;

	fd = open("/dev/gmem", O_RDWR);
	if(fd == -1)
	{
		perror("error");
		return -1;
	}
	//读写测试
	if(write(fd, wbuf, strlen(wbuf)) == -1)
		goto ERROR;
	if(lseek(fd, 0, SEEK_SET) == -1)
		goto ERROR;
	memset(rbuf, 0, sizeof(rbuf));
	if(read(fd, rbuf, sizeof(rbuf)) == -1)
		goto ERROR;
	printf("read1:%s\r\n", rbuf);

	//获取之前的大小
	if(ioctl(fd, GMEM_GET_SIZE, &gmem_size) == -1)
		goto ERROR;
	printf("gmem_size1 =%d\r\n", gmem_size);
	//设置新的大小
	if(ioctl(fd, GMEM_SET_SIZE, 20) == -1)
		goto ERROR;
	//获取新设置的大小
	if(ioctl(fd, GMEM_GET_SIZE, &gmem_size) == -1)
		goto ERROR;
	printf("gmem_size2 =%d\r\n", gmem_size);
	if(lseek(fd, 0, SEEK_SET) == -1)
		goto ERROR;
	//再次读取
	memset(rbuf, 0, sizeof(rbuf));
	if(read(fd, rbuf, sizeof(rbuf)) == -1)
		goto ERROR;
	printf("read2:%s\r\n", rbuf);

	//清空gmem
	if(ioctl(fd, GMEM_CLEAN) == -1)
		goto ERROR;
	if(lseek(fd, 0, SEEK_SET) == -1)
		goto ERROR;
	//再次读取
	memset(rbuf, 0, sizeof(rbuf));
	if(read(fd, rbuf, sizeof(rbuf)) == -1)
		goto ERROR;
	printf("read3:%s\r\n", rbuf);

	//读写测试
	if(write(fd, wbuf, strlen(wbuf)) == -1)
		goto ERROR;
	if(lseek(fd, 0, SEEK_SET) == -1)
		goto ERROR;
	memset(rbuf, 0, sizeof(rbuf));
	if(read(fd, rbuf, sizeof(rbuf)) == -1)
		goto ERROR;
	printf("read4:%s\r\n", rbuf);

	close(fd);
	return 0;
ERROR:
	perror("error");
	close(fd);
	return -1;
}
